<template>
  <div class="container">
    <Header></Header>
    <div class="logo">
      <img :src="logo" alt="" width="150" />
      <img :src="mnnu" alt="" />
    </div>
    <CarAddress :address="address" @changeAddr="changeAddr" @deliveryAddr="deliveryAddr"></CarAddress>
    <CarTop @seleteAll="checkAll" :chose="checkedAll"></CarTop>
    <div v-if="items.shopcart.length > 0">
      <CarItem v-for="item in items.shopcart" :key="item._id" :itemname="item.goods.name" :price="item.goods.price" :quantity="item.quantity" :id="item._id" :img="item.goods.cover" @syncData="setData" :seleted="item.checked" @sendchecked="sendChecked" @deleteItem="deleteItem"></CarItem>
    </div>
    <img v-else :src="emptycart" alt="" width="400" style="margin-left: 600px; user-select: none;" />
    <CarBottom class="fix" @seleteAll="checkAll" :chose="checkedAll" :quantity="quantity" :total="total" :mark="mark" @clearAll="clearAll" @confirm="handleConfirm"></CarBottom>
    <!-- <footer></footer> -->
    <div>
      <el-dialog title="确定购买" :visible.sync="outerVisible">
        <el-dialog width="30%" title="选择配送方式" :visible.sync="innerVisible" append-to-body>
          <div slot="footer" class="dialog-footer">
            <el-button @click="delivery('到店自取', total)">到店自取</el-button>
            <el-button type="primary" @click="delivery('速递员配送', total + 1)">+1元配送</el-button>
          </div>
        </el-dialog>
        <div slot="footer" class="dialog-footer">
          <el-button @click="outerVisible = false">取 消</el-button>
          <el-button type="primary" @click="innerVisible = true">去支付</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Header from '@/components/base/header.vue'
import logo from '@/assets/logo.png'
import mnnu from '@/assets/image/mnnu.png'
import CarItem from '@/components/base/caritem.vue'
import CarTop from '@/components/base/cartop.vue'
import CarBottom from '@/components/base/carbottom.vue'
import { order, getShoppingCart, editShopCart, getAddress, modifyAddress } from '@/api/index.js'
import CarAddress from '@/components/base/cartAddress.vue'
import emptycart from '@/assets/image/emptycart.svg'
export default {
  components: {
    Header,
    CarItem,
    CarTop,
    CarBottom,
    CarAddress
  },
  data() {
    return {
      logo,
      mnnu,
      items: {},
      checkedAll: false,
      quantity: 0,
      total: 0,
      mark: false,
      address: [],
      deliveryAddress: '',
      outerVisible: false,
      innerVisible: false,
      emptycart
    }
  },
  methods: {
    // 请求购物车数据
    async getData(url, params) {
      const { data } = await getShoppingCart(url, params)
      this.items = data
      this.result(this.items.shopcart)
    },
    // 修改购物车数据
    setData(e) {
      const index = this.items.shopcart.findIndex(v => e.id === v._id)
      this.items.shopcart[index].total = e.total
      this.items.shopcart[index].quantity = e.quantity
      this.result(this.items.shopcart)
    },
    checkAll(e) {
      this.checkedAll = e
      this.items.shopcart.forEach(element => {
        element.checked = e
      })
      this.result(this.items.shopcart)
    },
    sendChecked(e) {
      const index = this.items.shopcart.findIndex(v => e.id === v._id)
      this.items.shopcart[index].checked = e.checked
      this.checkedAll = this.items.shopcart.every(item => item.checked === true)
      this.result(this.items.shopcart)
    },
    result(arr) {
      let total = 0
      let quantity = 0
      this.mark = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked === true) {
          this.mark = true
          total = total + arr[i].total
          quantity = quantity + arr[i].quantity
        }
      }
      this.total = total
      this.quantity = quantity
    },
    deleteItem(id) {
      const index = this.items.shopcart.findIndex(v => v._id === id)
      this.items.shopcart.splice(index, 1)
    },
    async modify(url, data) {
      await editShopCart(url, data)
    },
    // 清空购物车
    clearAll() {
      this.items.shopcart = []
    },
    // 获取地址
    async getAddr(url, params) {
      const { data } = await getAddress(url, params)
      this.address = data.address
    },
    // 修改地址
    async postAddr(url, data) {
      await modifyAddress(url, data)
    },
    changeAddr(address) {
      this.address = address
    },
    // 获取最终配送地址
    deliveryAddr(address) {
      this.deliveryAddress = address
    },
    // 点击结算
    handleConfirm() {
      if (this.deliveryAddress === '') {
        return this.open()
      }
      this.outerVisible = true
    },
    // 到店自取
    // nodelivery() {
    //   this.innerVisible = false
    //   this.outerVisible = false
    //   this.finally('到店自取', this.total)
    //   this.quantity = 0
    //   this.total = 0
    //   this.checkedAll = false
    // },
    delivery(method, total) {
      this.innerVisible = false
      this.outerVisible = false
      this.finally(method, total)
      this.quantity = 0
      this.total = 0
      this.mark = false
      this.checkedAll = false
    },
    open() {
      this.$alert('请选择收货地址', {
        confirmButtonText: '确定'
      })
    },
    // 发送订单
    async sendOrder(url, data) {
      await order(url, data)
    },
    finally(method, total) {
      const seleted = this.items.shopcart.filter(item => item.checked)
      const unseleted = this.items.shopcart.filter(item => !item.checked)
      this.items.shopcart = unseleted
      this.modify('/api/home/modify', JSON.stringify(this.items))
      const start = Date.now()
      const end = start + 30 * 60 * 1000
      let deliveryAddress = ''
      if (method === '到店自取') {
        deliveryAddress = '----------'
      } else {
        deliveryAddress = this.deliveryAddress
      }
      const Order = {
        custom: this.items.custom,
        goods: seleted,
        total,
        deliveryAddress,
        method,
        start,
        end
      }
      this.sendOrder('/api/home/postorder', Order)
    }
  },
  created() {
    const customId = JSON.parse(JSON.parse(localStorage.getItem('accessToken')).data)
    this.getData('/api/home/getshoppingcart', { customId })
    this.getAddr('/api/home/address', { id: customId })
  },
  destroyed() {
    this.modify('/api/home/modify', JSON.stringify(this.items))
    this.postAddr('/api/home/modifyaddress', { id: this.items.custom, address: this.address })
  },
  mounted() {
    window.addEventListener('beforeunload', e => {
      this.modify('/api/home/modify', JSON.stringify(this.items))
      this.postAddr('/api/home/modifyaddress', { id: this.items.custom, address: this.address })
      this.getAddr('/api/home/address', { id: this.items.custom })
    })
  }
}
</script>

<style lang="less" scoped>
.container {
  user-select: none;
  .logo {
    margin-left: 150px;
    margin-top: 30px;
  }
  .fix {
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
  }
  //   footer {
  //     height: 30px;
  //   }
}
</style>
